package org.flashbrighton.as3bots.views.ui 
{
	import flash.display.*;
	import flash.events.*;
	import flash.text.*;
	import flash.utils.Timer;
	
	public class Alert extends Sprite
	{
		private static var BOX_WIDTH:int = 380;
		private static var BOX_HEIGHT:int = 120;
		private static var PADDING_X:int = 5;
		private static var PADDING_Y:int = 5;
		
		private var _tf:TextField;
		private var _timer:Timer;
		private var _isFlashing:Boolean;
		
		public function Alert() 
		{
			init();
		}
		
		
		public function setText(s:String):void
		{
			_tf.text = s;
			
			// Decrease font size until the text fits  
			var fmt:TextFormat = _tf.getTextFormat();			
			while (_tf.textWidth > BOX_WIDTH - PADDING_X * 2 || _tf.textHeight > BOX_HEIGHT - PADDING_Y * 2) 
			{
				fmt.size = int(fmt.size) - 1;
				_tf.setTextFormat(fmt);
			}
			
			// Vertically centre text
			_tf.y = -_tf.height / 2;
		}
		
		
		public function show(s:String=null):void 
		{
			if (s) setText(s);
			_timer.start();
		}
		
		
		public function blink(s:String):void
		{
			_isFlashing = true;
			show(s);
		}
		
		
		private function init():void
		{
			addChild(createBox());
			addChild(createText());
			
			_timer = new Timer(300, 5);
			_timer.addEventListener(TimerEvent.TIMER, flash);
			_timer.addEventListener(TimerEvent.TIMER_COMPLETE, notifyComplete);
			
			_isFlashing = false;
			this.visible = false;
		}
		
		
		private function createBox():Shape
		{
			var s:Shape = new Shape();
			s.graphics.lineStyle(2, 0xFFFFFF);
			s.graphics.beginFill(0x000000, 0.5);
			s.graphics.drawRect(-BOX_WIDTH / 2, -BOX_HEIGHT / 2, BOX_WIDTH, BOX_HEIGHT);
			s.graphics.endFill();
			return s;
		}
		
		
		private function createText():TextField
		{
			var tformat:TextFormat = new TextFormat("Arkitech", 40, 0xFFFFFF);
			tformat.align = TextFormatAlign.CENTER;
			
			_tf = new TextField();
			_tf.embedFonts = true;
			_tf.defaultTextFormat = tformat;	
			_tf.width = BOX_WIDTH - PADDING_X * 2;
			_tf.height = BOX_HEIGHT - PADDING_Y * 2;
			_tf.multiline = true;
			_tf.wordWrap = true;
			_tf.autoSize = TextFieldAutoSize.CENTER;
			_tf.selectable = false;
			_tf.x = -BOX_WIDTH / 2 + PADDING_X;
			_tf.y = -BOX_HEIGHT / 2 + PADDING_Y;
			
			return _tf;
		}
		
		
		private function notifyComplete(e:TimerEvent):void 
		{
			_timer.reset();
			
			if (_isFlashing)
			{
				dispatchEvent(new Event(Event.COMPLETE));
				_isFlashing = false;
				this.visible = false;
			}
		}
		
		
		private function flash(e:TimerEvent=null):void
		{
			this.visible = !this.visible;
		}
		
	}

}